#-*- coding:utf-8 -*-
import MySQLdb,codecs,os,sys,datetime,time,random,requests,hashlib,simplejson,urllib
import settings
from django.shortcuts import render_to_response
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse,HttpResponseRedirect,HttpResponseForbidden,HttpResponseNotFound,HttpResponsePermanentRedirect
from datetime import timedelta, date 
from dict2xml import dict2xml
from django.core.cache import cache
#from zz91page import *
reload(sys) 
sys.setdefaultencoding('utf-8') 
nowpath=os.path.dirname(__file__)
execfile(nowpath+"/func/erm_function.py")
execfile(nowpath+"/func/ermtools.py")
execfile(nowpath+"/func/erm_db.py")
db=ermdb()

#主框架
def main(request):
    username = request.session.get('username', default=None)
    password = request.session.get('password', default=None)
    if not username:
        return HttpResponseRedirect("login.html")
    return render_to_response('main.html',locals())

def index(request):
    return render_to_response('index.html',locals())

def car_list(request):
    return render_to_response('car_list.html',locals())
def car_data(request):
    sql = "select id,qrcode,longitude,latitude,car_info from car"
    resultlist = db.fetchalldb(sql)
    l = []
    for result in resultlist:
	id = result[0]
	qrcode = result[1]
	longitude = result[2]
	latitude = result[3]
	car_info = result[4]
	d = {'id':id, 'qrcode':qrcode, 'longitude':longitude, 'latitude':latitude, 'car_info':car_info}
	l.append(d)
    list = {'code':0, 'msg':"", 'count':1, 'data':l}
    return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
    
def whoDriveCar(request): 
    print request
    if request.method == 'POST':
        qrcode = request.POST["qrcode"]
        longitude = request.POST["longitude"]
        latitude = request.POST["latitude"]
        car_info = request.POST["car_info"]
        sql = "INSERT INTO car (qrcode, longitude, latitude, car_info) VALUES ('%s','%s','%s','%s')" % (qrcode,longitude,latitude,car_info)
        result = db.updatetodb(sql)
        list = {'code':0, 'msg':"添加成功"}
        return HttpResponse(simplejson.dumps(list, ensure_ascii=False))
    else :
        msg = {'msg':"不是POST请求"}
        return HttpResponse(simplejson.dumps(msg, ensure_ascii=False))

def viewer_404(request):
    t = get_template('404.html')
    html = t.render(Context())
    return HttpResponseNotFound(html)
def viewer_500(request):
    t = get_template('404.html')
    html = t.render(Context())
    return HttpResponseNotFound(html)
